<?php

namespace Admin\Assist\Controllers;

use Helpers\User;
use Phalcon\Mvc\View;
use Phalcon\Mvc\Dispatcher;
use Phalcon\Mvc\Controller;
use Helpers\Main;

class ControllerBase extends Controller
{

    public function beforeExecuteRoute(Dispatcher $dispatcher)
    {
        //检查是否已登陆，否则跳转到登陆页面
        if (!User::isLogin()) {
            Main::goLoginPage();
//            return $this->response->redirect('index/login');
//            $this->dispatcher->forward([
//                'controller' => 'Index',
//                'action'     => 'login',
//            ]);
//            return false;
//            die('未登录无法操作');
        }

        return true;
    }

    private function createCommitLog($msg, $detail = null)
    {
        return Main::createCommitLog(
            'admin',
            $this->dispatcher->getControllerName(),
            $this->dispatcher->getActionName(),
            ['post' => $this->request->getPost(), 'get' => $this->request->getQuery(), 'detail' => $detail],
            null,
            $msg
        );
    }

    public function sendErrorResponse($code = 200, $error = '未知错误', $msg = null, $log = true)
    {
        $content = ['error' => $error, 'code' => $code];
        $msg and $content['msg'] = $msg;
        $log and $this->createCommitLog($error, $msg);
        return $this->response->setStatusCode($code)->setJsonContent($content, JSON_UNESCAPED_UNICODE);
    }

    public function sendSuccessResponse($msg = null, $log = true)
    {
        $log and $this->createCommitLog($msg);
        return $this->response->setJsonContent(['code' => 200, 'msg' => $msg ?: '成功！'], JSON_UNESCAPED_UNICODE);
    }

    public function sendJsonResponse($data = null, $log = false)
    {
        $log and $this->createCommitLog('json返回成功', $data);
        return $this->response->setJsonContent($data, JSON_UNESCAPED_UNICODE);
    }

    public function sendDataGridError($error, $msg = null, $log = true)
    {
        $content = ['error' => $error, 'total' => 0, 'rows' => []];
        $msg and $content['msg'] = $msg;
        $log and $this->createCommitLog($error, $msg);
        return $this->response->setJsonContent($content, JSON_UNESCAPED_UNICODE);
    }

    public function sendViewError($error)
    {
        $this->view->disableLevel([
            View::LEVEL_LAYOUT,
            View::LEVEL_BEFORE_TEMPLATE,
            View::LEVEL_AFTER_TEMPLATE,
            View::LEVEL_ACTION_VIEW,
        ]);
        return $this->flash->error($error);
    }

    public function sendViewSuccess($msg)
    {
        $this->view->disableLevel([
            View::LEVEL_LAYOUT,
            View::LEVEL_BEFORE_TEMPLATE,
            View::LEVEL_AFTER_TEMPLATE,
            View::LEVEL_ACTION_VIEW,
        ]);
        return $this->flash->success($msg);
    }

}